package com.ezjie.ielts.module_personal;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.PopupWindow.OnDismissListener;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.constant.Constants;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.db.UserInfoDB;
import com.ezjie.ielts.model.UploadPhotoData;
import com.ezjie.ielts.model.UploadPhotoResponse;
import com.ezjie.ielts.module_set.FeedbackActivity;
import com.ezjie.ielts.module_set.SettingActivity;
import com.ezjie.ielts.task.UploadPhotoTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.ImageUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.view.CircleImageViewva;
import com.ezjie.ielts.widget.TitleTextView;
import com.ezjie.login.LoginActivity;
import com.ezjie.login.model.UserDetail;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.umeng.analytics.MobclickAgent;

@ContentView(R.layout.layout_profile)
public class PersonalActivity extends BaseFragmentActivity {
	private static final int REQUEST_CODE = 111;

	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.iv_topbar_right)
	private ImageView iv_topbar_right;
	@ViewInject(R.id.tv_topbar_title)
	private TitleTextView tv_topbar_title;
	
	@ViewInject(R.id.nick_name_text)
	private TextView nick_name_text;
	@ViewInject(R.id.my_goal_info)
	private RelativeLayout my_goal_info;
	@ViewInject(R.id.profile_image)
	private CircleImageViewva profile_image;
	@ViewInject(R.id.empty_view)
	private View empty_view;

	private UserDetail info;
	private UserInfoDB userInfoDB;
	private static DisplayImageOptions options;
	private UploadPhotoTask uploadPhotoTask;
	/***********修改头像**********/
	private String uploadPath;
	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;
	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera"
			);
	private static File mCurrentPhotoFile;// 照相机拍照得到的图片

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);

		init();
		
		uploadPhotoTask = new UploadPhotoTask(this);
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ph_head_icon)  //设置图片在下载期间显示的图片
		.showImageForEmptyUri(R.drawable.ph_head_icon)  //设置图片Uri为空或是错误的时候显示的图片
		.showImageOnFail(R.drawable.ph_head_icon)  // 设置图片加载/解码过程中错误时候显示的图片
		.cacheInMemory(true)  //是否緩存都內存中
		.cacheOnDisc(true)  //是否緩存到sd卡上
		//.displayer(new RoundedBitmapDisplayer(20))设置成圆角图片
		.build();
		/*ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).build();
		ImageLoader.getInstance().init(
				config);*/
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_PERSONAL);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_PERSONAL);
	}

	private void init() {
		userInfoDB = new UserInfoDB(this);
		info = userInfoDB.queryLoginUser();
		if (info != null && !TextUtils.isEmpty(info.nick_name)&&nick_name_text!=null) {
			nick_name_text.setText(info.nick_name);
			if (profile_image != null && !TextUtils.isEmpty(info.head_url)) {
				ImageLoader.getInstance().displayImage(info.head_url, profile_image, options);
			}
			
		}

		iv_topbar_right.setVisibility(View.VISIBLE);
		iv_topbar_right.setOnClickListener(this);
		iv_topbar_back.setOnClickListener(this);
		tv_topbar_title.setText(R.string.personal_title);
		my_goal_info.setOnClickListener(this);
		empty_view.setOnClickListener(this);
		
		initPhotoWindow();
	}
	
	private PopupWindow photoPopupWindow;
	private void initPhotoWindow() {
		View view = LayoutInflater.from(this).inflate(
				R.layout.profile_choose_photo, null);
		photoPopupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);

		// 需要设置一下此参数，点击外边可消失
		photoPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击窗口外边窗口消失
		photoPopupWindow.setOutsideTouchable(true);
		// 设置此参数获得焦点，否则无法点击
		photoPopupWindow.setFocusable(true);
		photoPopupWindow.setAnimationStyle(R.style.exitStyle);
		photoPopupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				//当点击back的时候，让empty_view消失
				empty_view.setVisibility(View.GONE);
			}
		});

		View blank = view.findViewById(R.id.blank);
		blank.setOnClickListener(this);
		TextView tv_camera = (TextView) view.findViewById(R.id.tv_camera);
		tv_camera.setOnClickListener(this);
		TextView tv_photo = (TextView) view.findViewById(R.id.tv_photo);
		tv_photo.setOnClickListener(this);
		TextView tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
		tv_cancel.setOnClickListener(this);
	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			finish();
			break;
		case R.id.my_goal_info:
			startActivity(new Intent(PersonalActivity.this, ChangeAimActivity.class));
			break;
		case R.id.iv_topbar_right:
			//设置
			Intent intent = new Intent(PersonalActivity.this, SettingActivity.class);
			startActivityForResult(intent, REQUEST_CODE);
			break;
		case R.id.tv_cancel:
		case R.id.blank:
			photoPopupWindow.dismiss();
			empty_view.setVisibility(View.GONE);
			break;
		case R.id.tv_camera:
			String status = Environment
			.getExternalStorageState();
			if (status.equals(Environment.MEDIA_MOUNTED)) {
				doTakePhoto();
			} else {
				AppUtil.showToast(this, "外部存储不可用");
			}
			photoPopupWindow.dismiss();
			empty_view.setVisibility(View.GONE);
			break;
		case R.id.tv_photo:
			// 相册
			doPickPhotoFromGallery();
			photoPopupWindow.dismiss();
			empty_view.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}
	
	@OnClick(R.id.profile_image)
	private void onPhotoClick(View view){
		choosePhoto(view);
	}
	
	/**************修改头像********************/
	private void choosePhoto(View v){
		showPhotoPopupWindow(v);
		empty_view.setVisibility(View.VISIBLE);
	}
	
	private void showPhotoPopupWindow(View v) {
		photoPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
	}
	
	/**
	 * 拍照
	 */
	private void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			boolean dd = PHOTO_DIR.mkdirs();// 创建照片的存储目录
			mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			AppUtil.showToast(this, "没有照相机程序");
		}
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	/**
	 * 从图库选择
	 */
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			PHOTO_DIR.mkdirs();
			mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());
			final Intent intent = getPhotoPickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			AppUtil.showToast(this, "not find photo");
		}
	}

	public static Intent getPhotoPickIntent(File f) {
		Intent intent = new Intent("android.intent.action.PICK");
		intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI,
				"image/*");
		// intent.putExtra("output", Uri.fromFile(f));
		return intent;
	}

	/**
	 * 用当前时间给取得的图片命名
	 * 
	 */
	public static String getPhotoFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == REQUEST_CODE ) {
			startActivity(new Intent(this,LoginActivity.class));
			this.finish();
		}
		if (resultCode == Activity.RESULT_OK) {
			//拍照相关
			if (requestCode == CAMERA_WITH_DATA) {
				// 拍照返回的
				// 进行压缩到240x240的
				if (mCurrentPhotoFile != null) {
					Bitmap bitmap = ImageUtil
							.parseHeadBitmapToLittle(mCurrentPhotoFile
									.getPath());
					//将压缩后的bitmap保存到sd卡中
					uploadPath = new File(PHOTO_DIR, getPhotoFileName()).getPath();
					ImageUtil.saveImageToSD(uploadPath, bitmap);

					profile_image.setImageBitmap(bitmap);

					uploadPhoto();
				}

			} else if (requestCode == PHOTO_PICKED_WITH_DATA) {
				// 从图库选择的
				ContentResolver cr = this.getContentResolver();
				String path = ImageUtil.getUriString(data.getData(), cr);
				Bitmap bitmap = ImageUtil
						.parseHeadBitmapToLittle(path);
				//将压缩后的bitmap保存到sd卡中
				uploadPath = new File(PHOTO_DIR, getPhotoFileName()).getPath();
				ImageUtil.saveImageToSD(uploadPath, bitmap);

				profile_image.setImageBitmap(bitmap);
				uploadPhoto();
			}
		}
	}
	
	private void uploadPhoto(){
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return; 
		}
		uploadPhotoTask.uploadPhoto(uploadPath, new HttpRequestAbstractCallBack(this,true) {
			@Override
			public void onStartCallBack() {
				// TODO Auto-generated method stub
				super.onStartCallBack();
				AppUtil.showProgressDialog(PersonalActivity.this);
			}
			@Override
			public void onSuccessCallBack(String result) {
				// TODO Auto-generated method stub
				super.onSuccessCallBack(result);
				AppUtil.dismissProgressDialog();
				LogUtils.d(result);
				try {
					UploadPhotoResponse greSpeakFilterResponse = JSON.parseObject(result,
							UploadPhotoResponse.class);
					if(greSpeakFilterResponse != null && greSpeakFilterResponse.getStatus_code() == 200){
						UploadPhotoData data = greSpeakFilterResponse.getData();
						if (data != null) {
							String status = data.getStatus();
							if ("1".equals(status)) {
								AppUtil.showToast(PersonalActivity.this, R.string.profile_upload_success);
								//String url = data.getUrl();
								//替换保存用户的头像
								if (info != null) {
									info.head_url = "file://"+uploadPath;
									LogUtils.d("上传后头像路径："+info.head_url);
									userInfoDB.update(info);
								}
							}else {
								AppUtil.showToast(PersonalActivity.this, data.getMessage());
							}
						}
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}
			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				// TODO Auto-generated method stub
				super.onFailureCallBack(error, msg);
				AppUtil.dismissProgressDialog();
        		AppUtil.showToast(PersonalActivity.this, R.string.load_net_data_failure);
			}
		});
	}

}
